home *** CD-ROM | disk | FTP | other *** search
/ NetNews Offline 2 / NetNews Offline Volume 2.iso / news / comp / lang / c++-part1 / 9456 < prev    next >
Encoding:
Text File  |  1996-08-05  |  2.1 KB  |  60 lines

  1. Path: ausnews.austin.ibm.com!usenet
  2. From: Leo Uzcategui <leou@austin.ibm.com>
  3. Newsgroups: comp.lang.c++
  4. Subject: Re: STL: for_each vs transform
  5. Date: Fri, 01 Mar 1996 14:41:16 -0600
  6. Organization: IBM Corp.
  7. Message-ID: <313760EC.41C6@austin.ibm.com>
  8. References: <3135F631.41C6@austin.ibm.com> <4h7ems$6v@druid.borland.com>
  9. NNTP-Posting-Host: socks.austin.ibm.com
  10. Mime-Version: 1.0
  11. Content-Type: text/plain; charset=us-ascii
  12. Content-Transfer-Encoding: 7bit
  13. X-Mailer: Mozilla 2.0 (X11; I; AIX 1)
  14.  
  15. Pete Becker wrote:
  16. > In article <3135F631.41C6@austin.ibm.com>, leou@austin.ibm.com says...
  17. > >
  18. > >How can iterate thru a container, using for_each, and apply a function
  19. > >object which modifies each of the elements in the container?
  20. > >I tried passing the argument by name, but the template definition
  21. > >will not allow it.
  22. > >
  23. > >Here's the example: Note addr and size values never change.
  24. > >
  25. > >#include    <iostream.h>
  26. > >#include    <algo.h>
  27. > >#include    <vector.h>
  28. > >
  29. > >struct S { vector<int> v; };
  30. > >struct g : public binary_function<S,int,int> {
  31. > >    int operator()(S s,int x) const
  32. > >    {s.v.push_back(x);
  33. > >    cout<<"x="<<x<<endl;
  34. > >    cout<<"g() addr of s:"<<(size_t)&s<<" size of v:"<<s.v.size()<<endl;
  35. > >    return 0;};
  36. > >};
  37. > >
  38. > >void main() {
  39. > >vector<S> A(3); // A has 3 vector<int>'s
  40. > >for (int i=0; i<2; i++)
  41. > >    for_each( A.begin(),A.end(), bind2nd(g(),i) );
  42. > >}
  43. > I made three changes in the first few lines of this code. None of them affect
  44. > the legality of the call to for_each. With those changes, this code compiled
  45. > just fine with BC++ 5.0. Here are the changed lines:
  46. > #include    <iostream.h>
  47. > #include    <algorothm>         // 1: ANSI/ISO header name
  48. > #include    <vector>            // 2: ANSI/ISO header name
  49. > using namespace std;            // 3: these things live in namespace std
  50.  
  51. The sample code compiles and works OK for me too. My question was how
  52. to pass by name the 1st argument to the function invoked by for-each().
  53. I thought of using transform(), but its definition doesn't quite fit
  54. the problem here since the binary function used in transform, requires
  55. two containers.
  56.